import store from '@/store'
import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'

import {
	v4 as uuidv4
} from 'uuid'
import {
	encryptHmac
} from './jsencrypt'

import storage from '@/utils/storage'
let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
	// 是否需要设置 token
	const isToken = (config.header || {}).isToken === false
	config.header = config.header || {};
	config.method = config.method || 'get';
	const secret = uni.getStorageSync('secret')
	// 是否需要防止数据重复提交
	const isRepeatSubmit = (config.header || {}).repeatSubmit === false
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
	}
	// get请求映射params参数
	// if (config.params) {
	//   let url = config.url + '?' + tansParams(config.params)
	//   url = url.slice(0, -1)
	//   config.url = url
	// }
	let timestamp = new Date().getTime();
	let nonce = uuidv4();

	config.header['timestamp'] = timestamp;
	config.header['nonce'] = nonce;

	if (config.method === 'get') {
		let signData = '';
		if (config.params) {
			signData = tansParams(config.params);
			signData = signData.slice(0, -1);
		}
		signData += timestamp + nonce;
		console.log(signData);
		config.header['sign'] = encryptHmac(signData, secret);
	}
	if (config.method === 'get' && config.params) {
		let url = config.url + '?' + tansParams(config.params);
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}

	if (config.method === 'post' || config.method === 'put') {

		const signData = (config.data ? JSON.stringify(config.data) : '{}') + timestamp + nonce;
		console.log(signData)
		config.header['sign'] = encryptHmac(signData, secret);
	}
	if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
		const requestObj = {
			url: config.url,
			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
			time: new Date().getTime()
		}
		const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
		const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
		if (requestSize >= limitSize) {
			console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。')
			return config;
		}
		const sessionObj = storage.get('sessionObj');
		if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
			storage.set('sessionObj', requestObj)
		} else {
			const s_url = sessionObj.url; // 请求地址
			const s_data = sessionObj.data; // 请求数据
			const s_time = sessionObj.time; // 请求时间
			const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
			if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
				const message = '数据正在处理，请勿重复提交';
				console.warn(`[${s_url}]: ` + message)
				return Promise.reject(new Error(message))
			} else {
				storage.set('sessionObj', requestObj)
			}
		}
	}

	return new Promise((resolve, reject) => {
		console.log('header', config.header)
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {
				let [error, res] = response
				if (error) {
					toast('后端接口连接异常')
					reject('后端接口连接异常')
					return
				}
				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']

				console.log(config.url, '/student/bindWechat')
				if (code === 401) {
					// 判断是否是扫码登陆
					const launchOptions = wx.getLaunchOptionsSync();
					if(launchOptions.scene == 1047){
						wx.setStorageSync('launchOptions',launchOptions)
					}
					if (getToken()) {
						showConfirm('登录状态已过期，请重新登录授权').then(res => {
							if (res.confirm) {
								console.log('授权微信登录');
								store.commit("SET_WXLOGINPOPVISIBLE", true)
								store.dispatch('LogOut').then(res => {
									uni.reLaunch({
										url: '/pages/login'
									})
								})
							}
						})
					} else {
						showConfirm('未登录, 是否去登录').then(res => {
							if (res.confirm) {
								store.dispatch('LogOut').then(res => {
									uni.reLaunch({
										url: '/pages/login'
									})
								})

							}
						})
					}

					reject('无效的会话，或者会话已过期，请重新登录。')

				} else if (code === 500) {
					toast(msg)
					reject('500')
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				resolve(res.data)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
				reject(error)
			})
	})
}

export default request